package javaweb.selectcclass.test.controller;

import javaweb.selectcclass.test.entity.Course;
import javaweb.selectcclass.test.entity.Submit;
import javaweb.selectcclass.test.entity.User;
import javaweb.selectcclass.test.repo.CourseRepo;
import javaweb.selectcclass.test.repo.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

@Controller
public class HomeController {

    @Autowired
    UserRepo userRepo;
    @Autowired
    CourseRepo courseRepo;

    @GetMapping("/home")
    public String home(Model model){
        User user = userRepo.findByStuId("1825121000");
        System.out.println(user);
        model.addAttribute("user", user);
        return "home";
    }

    @GetMapping("/")
    public String index(){
        return "index";
    }

    @GetMapping("/select")
    public String select(Model model) {
        List<Course> list = courseRepo.findAll();
        model.addAttribute("courses", list);
        return "select";
    }

    @PostMapping("/select")
    public String send(@Valid Submit submit, Errors errors, Model model) {
        User user = userRepo.findByStuId("1825121000");
        if(errors.hasErrors()) {
            model.addAttribute("err", "err");
            return select(model);
        }
        model.addAttribute("user", user);
        List<String> stringList = submit.getCourses();
        user.getCourses().clear();
        for (String courseId:stringList
             ) {
            user.getCourses().add(new Course(courseId, null, null));
        }
        userRepo.save(user);
        user = userRepo.findByStuId("1825121000");
        model.addAttribute("course", user.getCourses());
        return "send";
    }
}
